﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace GestorDeFlotasDesktop.Facturar
{
    public partial class Listado_Factura : Form
    {
        private DataTable dt;

        public Listado_Factura(int cliente_id, DateTime f_ini, DateTime f_fin)
        {
            InitializeComponent();
            tb_fini.Text = f_ini.Date.ToShortDateString();
            tb_ffin.Text = f_fin.Date.ToShortDateString(); 
            FillData(cliente_id, f_ini, f_fin);
        }

        void FillData(int cliente_id, DateTime f_ini, DateTime f_fin)
        {
            using (SqlConnection con = Modelo.Modelo.createConnection())
            {
                SqlDataAdapter da;
                dt = new DataTable();
                da = new SqlDataAdapter(Modelo.SqlQueries.getFacturas(cliente_id, f_ini, f_fin), con);
                da.Fill(dt);
 
                dataGridView1.DataSource = dt;
            }
            using (SqlConnection con2 = Modelo.Modelo.createConnection())
            {
                Modelo.Modelo.openConnection(con2);
                SqlCommand comando_up_fact = new SqlCommand(Modelo.SqlQueries.updateFacturas(cliente_id, f_ini, f_fin), con2);
                comando_up_fact.ExecuteNonQuery();
            }

            double total = 0;
            foreach (DataRow dr in dt.Rows)
            {
                if (dr.RowState != DataRowState.Deleted)
                    total += Convert.ToDouble(dr["Importe"]);
            }
            tb_importe.Text = total.ToString();

            using (SqlConnection con3 = Modelo.Modelo.createConnection())
            {
                Modelo.Modelo.openConnection(con3);
                SqlCommand comando_up_fact = new SqlCommand(Modelo.SqlQueries.insertFacturas(cliente_id, f_ini, f_fin, Convert.ToDouble(tb_importe.Text)), con3);
                comando_up_fact.ExecuteNonQuery();
            }
        }
    }
}
